package com.fanyouzhao.ehome.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * @author 范友钊
 * @date 2021年3月19日 上午10:29:14
 */
public class SeriUtil {

	/**
	 * 对任意目标对象实现序列化操作，并存储到文件中
	 * @param path 目标文件的路径
	 * @param object 需要序列化存储的任意目标对象
	 */
	public static void objectToSeriFile(String path,Object object) {
		//将所有操作序列化方式保存到文件user.obj中，实现持久化
		File file =new File(path);
		try (FileOutputStream fileOutputStream = new FileOutputStream(file);
			 ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);) {
			objectOutputStream.writeObject(object);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static Object objectFromSeriFile(File file) {

		//执行反序列化
		Object object = null;
		try (FileInputStream fileInputStream = new FileInputStream(file);
			 ObjectInputStream objectInputStream =new ObjectInputStream(fileInputStream);
		) {
			object = objectInputStream.readObject();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return object;

	}
}